/*
 * ------------------------------------------------------------------
 * 服务器启动入口文件
 * ------------------------------------------------------------------
 * @关于我：
 * QQ:2815473064
 * wechat:13531609457
 * ------------------------------------------------------------------
 */
const express = require("express");
const routes = require("./router");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const app = express();
const Config = require("./config");
const WebSocket = require('ws');
const Redis = require("./sql/redis");
// HTTP ==============================================================
//配置解析application/x-www-form-urlencoded格式数据的中间件
app.use(express.urlencoded({ extended: false }));
//配置解析application/json格式的数据的中间件
app.use(express.json());
// 安装Cookie
app.use(cookieParser());
// 跨域配置
app.use(cors());
let HTTPConfig = Config.HTTP;
let { base, port } = HTTPConfig;
app.use(base, routes);
app.listen(port, () => {
  console.log("HTTP 服务启动成功 , 端口：", port);
});
// Websocket配置
let WsConfig = Config.WebSocket
// Websocket 端口
let WsPort = WsConfig.port
// 创建WebSocket服务器实例
const wss = new WebSocket.Server({ port: WsPort });
// 服务开启事件
wss.addListener("listening", () => {
  console.log('websocket 服务启动成功, 端口：', WsPort)
  console.log("");
})
// 服务关闭事件
wss.on('close', function close() {
  console.log('websocket 服务已关闭')
})
wss.on("error", (error) => {
  console.log("Websocket 服务启动失败");
})
// 服务客户端连接事件
wss.on('connection', async (WsClient, WsRequest) => {
  console.log('websocket 客户端连接成功')
  let tokenHeadersName = "sec-websocket-protocol"
  // 客户端IP地址
  let WsClientIp = WsRequest.socket.remoteAddress
  // 客户端请求头
  let WsClientHeaders = WsRequest.headers
  // 客户端token
  let token = WsClientHeaders[tokenHeadersName]

  if (!token) {
    WsClient.send(JSON.stringify({
      code: 0, msg: "收到您的消息,缺失认证token"
    }))
    // 踢出客户端
    WsClient.close()
  }
  // 客户端关闭事件
  WsClient.on("close", async (Client) => {
    console.log("客户端关闭事件", Client);
    await Redis.lRem(`TardeAdmin:Websocket:Client`, 0, JSON.stringify({
      ip: WsClientIp
    }))
    // Redis 自减
    await Redis.decr(`TardeAdmin:Websocket:Count`)
  })
  WsClient.on("error", (Client) => {
    console.log("客户端错误事件", Client);
  })
  WsClient.on("message", (e) => {
    let ClientMessage = JSON.parse(e)
    let MessageTypeOf = typeof ClientMessage
    if (MessageTypeOf != "object") {
      WsClient.send(JSON.stringify({
        code: 0, msg: "收到您的消息,未知的会话类型"
      }))
      return
    }
    let { type, action } = ClientMessage
    console.log({
      type, action
    });

    if (type == "credentials") {

      let { data } = ClientMessage

      let { token } = data

      if (token) {
        WsClient.Token = token
        WsClient.send(JSON.stringify({
          code: 0, msg: "您的密钥已登记"
        }))
      } else {
        WsClient.send(JSON.stringify({
          code: 0, msg: "您的密钥为空"
        }))
      }
    } else if (type == "Conversation") {

    }
  })
})